package com.bauer.module.framework.http;

import com.alibaba.fastjson.JSON;
import com.bauer.module.framework.constant.Constant;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author ：rui.wei
 * @Date ：Created in 12:31 2019/9/27
 * @Description：
 */
@WebFilter("/**")
@Component
public class HttpLogFilter extends OncePerRequestFilter {

    private static Logger logger = LoggerFactory.getLogger("http.request.log");


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        Long start = System.currentTimeMillis();
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
        HttpLogModel httpLogModel = new HttpLogModel();
        httpLogModel.setRequestBody(requestWrapper.getParameterMap());
        httpLogModel.setRequestHeader(getRequestHeaders(requestWrapper));

        filterChain.doFilter(requestWrapper, responseWrapper);
        String responseBody = new String(responseWrapper.getContentAsByteArray(), "UTF-8");
        httpLogModel.setResponseBody(responseBody);
        Long useTime = System.currentTimeMillis() - start;
        if (useTime > Constant.SLOW_REQUEST_MILL_SECONDS_LIMIT) {
            logger.error("USE_TIME:{}ms URL:{},REQUEST_INFO :{} ", useTime, requestWrapper.getRequestURI(), JSON.toJSONString(httpLogModel));
        } else {
            logger.info("USE_TIME:{}ms URL:{},REQUEST_INFO :{} ", useTime, requestWrapper.getRequestURI(), JSON.toJSONString(httpLogModel));
        }

        responseWrapper.copyBodyToResponse();

    }


    private Map<String, String> getRequestHeaders(HttpServletRequest request) {
        Map<String, String> headers = new HashMap<>(10);
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headers.put(headerName, request.getHeader(headerName));
        }
        return headers;

    }
}
